<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2017 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 李邦琦 <1536549251@qq.com>
// +----------------------------------------------------------------------

namespace app\moblie\controller;
use think\Db;

class Index extends Moblie {
	/**
	 * 会员登陆
	 */
	public function login()
	{
		$username = $_REQUEST['username'];
		$password = $_REQUEST['password'];
		$result = Db::name('sys_users')->where(array("username"=>$username,"password"=>$password))->find();
		// $a = $users->getlastsql();
		if (count($result)>0){
			if(!empty($result["phone"])){
				$data['status']  = 1;
				$data['username'] = $result['username'];
				$data['cn_name'] = $result['cn_name'];
				$data['phone'] = $result['phone'];
				$data['user_img'] = $result['user_img'];
				$data['ryToken'] = $result['ryToken'];
				$data['ryId'] = $result['ryId'];
				$data['msg'] = '账号正确';
			}else{
				$data['status']  = 2;
				$data['username'] = $result['username'];
				$data['cn_name'] = $result['cn_name'];
				$data['user_img'] = $result['user_img'];
				$data['ryToken'] = $result['ryToken'];
				$data['ryId'] = $result['ryId'];
				$data['msg'] = '未绑定手机号';
			}
			// file_put_contents('D:\phpStudy\WWW\qqqqqqqqqqqqqqq.php',$data);
			// $ajaxReturn['data'] = $data;
			// echo json_encode($ajaxReturn);
			$this->ajaxReturn($data);
		}else{
			$data['status']  = 0;
			$data['msg'] = '账号或密码错误';
			$this->ajaxReturn($data);
		}	
	}
	
	//更新群组信息
	public function updateUserInfo()
	{
		// $users = M("users");
		$username = $_REQUEST["username"];
		
		if(!empty($_FILES["file"]["name"][0])){
			$old_user_img = Db::name('sys_users')->field("user_img")->where("username = '$username'")->find();
			if($old_user_img){
				$oldSrc = 'include/data/headImg/'.$old_user_img['user_img'];
				unlink($oldSrc);
			}
			$res = $this->upload();
			$data['user_img'] = $res['0']['savename'];
		}
		if(!empty($_REQUEST["text"])){
			if($_REQUEST["type"]=="cn_name"){
				$data["cn_name"] = $_REQUEST["text"];
			}elseif($_REQUEST["type"]=="phone"){
				$data["phone"] = $_REQUEST["text"];
			}
		}
		$result = Db::name('sys_users')->where("username = '$username'")->update($data);
		if ($result!==false){
			$data['status']  = 1;
			$data['msg'] = '更新成功';
			$this->ajaxReturn($data);
		}else{
			$data['status']  = 0;
			$data['msg'] = '更新失败';
			$this->ajaxReturn($data);
		}	
		
	} 
	
	public function bindPhone()
	{
		$username = $_REQUEST["username"];
		$data["phone"] = $_REQUEST["phone"];
		// $users = M('users');
		$result = Db::name('sys_users')->where("username='$username'")->update($data);
		// $a = $users->getlastsql();
		//file_put_contents('/var/www/html/qqqqqqqqqqqqqqq.php',$a);
		if ($result!==false){
				$data['status']  = 1;
				$data['msg'] = '绑定成功';
			$this->ajaxReturn($data);
		}else{
			$data['status']  = 0;
			$data['msg'] = '绑定失败';
			$this->ajaxReturn($data);
		}	
	}
	
	
	public function getUserInfo()
	{
		$username = $_REQUEST["username"];
		// $users = M('users');
		$result = Db::name('sys_users')->alias("u")->join("xy_sys_department d", "d.d_id = u.d_id")->join("xy_sys_role r","r.r_id = u.r_id")->field("u.*,d.d_name,r.r_name")->where("username = '$username'")->find();
		if ($result!==false){
			$result['status']  = 1;
			$result['msg'] = '成功';
			$this->ajaxReturn($result);
		}else{
			$result['status']  = 0;
			$result['msg'] = '失败';
			$this->ajaxReturn($result);
		}	
		
		
	}
	
	public function getUsers(){
		$usersId = $_REQUEST["usersId"];
		// $users = M('users');
		$result = Db::name('sys_users')->field("ryId,cn_name")->where("username in($usersId)")->select();
		$this->ajaxReturn($result);
	}
	
	//消息列表转换
	public function getChatList(){
		$jsonStr = $_REQUEST["jsonStr"];
		$students= json_decode($jsonStr);//得到的是 object
		//file_put_contents('/var/www/html/aaaaa.php',$jsonStr);
		// $users = M("users");
		// $mobile_chat_group = M("mobile_chat_group");
		//$json_arr = array();
		//$i=0;
		foreach($students as &$obj){
			if($obj->conversationType=="PRIVATE"){
				$user_info = Db::name('sys_users')->where("ryId = '".$obj->targetId."'")->find();
				$obj->cn_name = $user_info["cn_name"];
				$obj->user_img = $user_info["user_img"];
			}else{
				$group_info = Db::name('mob_mobile_chat_group')->where("groupID = '".$obj->targetId."'")->find();
				$obj->cn_name = $group_info["groupName"];
				$obj->user_img = Db::name('sys_users')->field("user_img")->where("username in(".$group_info["member"].")")->limit(9)->select();
			}
			
			
			//$i++;
		} 
		$json = json_encode($students);
		$this->ajaxReturn($json);
	}
	
	//会话页消息历史记录转换
	function getChatHistory(){
		$jsonStr = $_REQUEST["jsonStr"];
		//file_put_contents('/var/www/html/aaaaa.php',$jsonStr);
		$students= json_decode($jsonStr);//得到的是 object
		// $users = M("users");
		foreach($students as &$obj){
			$user_info = Db::name('sys_users')->where("ryId = '".$obj->senderUserId ."'")->find();
			//$sql = $obj->senderUserId;
			$obj->cn_name = $user_info["cn_name"];
			$obj->user_img = $user_info["user_img"];
		} 
		$json = json_encode($students);
		
		$this->ajaxReturn($json);
	}
	
	//会话页接收新消息转换
	function newGroupMessage(){
		$jsonStr = $_REQUEST["jsonStr"];
		$students= json_decode($jsonStr);//得到的是 object
		// $users = M("users");
		$user_info = Db::name('sys_users')->where("ryId = '".$students->senderUserId."'")->find();
		$students->cn_name = $user_info["cn_name"];
		$students->user_img = $user_info["user_img"];
		$json = json_encode($students);
		$this->ajaxReturn($json);
		
	}
	
	//添加聊天记录到本地数据库
	function addMessage(){  
		$jsonStr = $_REQUEST["jsonStr"];
		//file_put_contents('/var/www/html/qqqqqqqqqqqqqqq.php',$jsonStr);
		$jsonArr= json_decode($jsonStr,true);
		// $mobile_chat_history = M("mobile_chat_history");
		$data["messageId"] = $jsonArr["messageId"];
		//$data["sentTime"] = $jsonArr["sentTime"];
		$data["sentTime"] = date("Y-m-d H:i:s");
		$data["conversationType"] = $jsonArr["conversationType"];
		$data["receivedStatus"] = $jsonArr["receivedStatus"];
		$data["messageDirection"] = $jsonArr["messageDirection"];
		$data["targetId"] = $jsonArr["targetId"];
		$data["objectName"] = $jsonArr["objectName"];
		$data["senderUserId"] = $jsonArr["senderUserId"];
		$data["receivedTime"] = $jsonArr["receivedTime"];
		if($jsonArr["objectName"]=="RC:TxtMsg"){
			$data["content"] = $jsonArr["content"]["text"];
		}elseif($jsonArr["objectName"]=="RC:ImgMsg"){
			$data["content"] = $jsonArr["content"]["imageUrl"];
		}elseif($jsonArr["objectName"]=="RC:VcMsg"){
			$data["content"] = $jsonArr["content"]["voicePath"];
		}
		
		$data["sentStatus"] = $jsonArr["sentStatus"];
		
		$result = Db::name('mob_mobile_chat_history')->data($data)->insert();
		
	}  
	
	//添加群组
	function addGroup(){  
		// $mobile_chat_group = M("mobile_chat_group");
		$data["groupId"] = $_REQUEST["groupID"];
		$data["groupName"] = $_REQUEST["groupName"];
		$data["member"] = $_REQUEST["usersId"];
		$data["createname"] = $_REQUEST["username"];
		
		$result = Db::name('mob_mobile_chat_group')->data($data)->insert();
		
	}
	
	//群组列表
	function groupList(){
		$username = $_REQUEST["username"];
		// $mobile_chat_group = M("mobile_chat_group");
		
		$result = Db::name('mob_mobile_chat_group')->where("find_in_set('$username', member)")->select();
		
		$this->ajaxReturn($result);
	}
	
	
	//群组信息
	function groupInfo(){
		// $mobile_chat_group = M("mobile_chat_group g");
		$targetId = $_REQUEST["targetId"];
		
		$result = Db::name('mob_mobile_chat_group')->alias("g")->join("xy_sys_users u", "u.username = g.createname")->field("u.cn_name,g.*")->where("g.groupID ='$targetId'")->find();
		$result["user_img"] = Db::name('sys_users')->field("cn_name,user_img")->where("username In(".$result["member"].")")->select();
		
		
		$this->ajaxReturn($result);
	}
	
	//更新群组信息
	function updateGroupInfo(){
		// $mobile_chat_group = M("mobile_chat_group");
		$targetId = $_REQUEST["targetId"];
		
		if(!empty($_FILES["file"]["name"][0])){
			$res = $this->upload();
			$data['img_file'] = $res['0']['savename'];
		}
		if(!empty($_REQUEST["groupName"])){
			$data["groupName"] = $_REQUEST["groupName"];
		}
		if(!empty($_REQUEST["val"])){
			$data["member"] = $_REQUEST["val"];
		}
		$result = Db::name('mob_mobile_chat_group')->where("groupId = '$targetId'")->update($data);
		
		
	} 
	
	//退出群组
	function quitDiscussion(){
		$username = $_REQUEST["username"];
		$targetId = $_REQUEST["targetId"];
		// $mobile_chat_group = M("mobile_chat_group");
		$sql = "UPDATE `mobile_chat_group` SET member = REPLACE(member,$username,' ') WHERE groupId='$targetId'";
		Db::query($sql);
		
	}

	/**
	 * 上传文件
	 */
	/*public function upload(){
        import('ORG.Net.UploadFile');
        $upload = new UploadFile();// 实例化上传类
        $upload->maxSize = 3145728 ;// 设置附件上传大小
        $upload->allowExts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->savePath = 'include/data/headImg/'; // 设置附件上传根目录
        $upload->autoSub = true;
        $upload->subType = 'date';
        // 上传文件
        if(!$upload->upload()) {// 上传错误提示错误信息
            $this->error($upload->getErrorMsg());
            return false;
        }else{// 上传成功 获取上传文件信息
            $info =  $upload->getUploadFileInfo();
            return $info;
        }
    }*/
	
	//设置上班时间
	function setTime(){
		$data["start_work_time"] = $_REQUEST["starttime"];
		$data["end_work_time"] = $_REQUEST["endtime"];
		// $mobile_work_time = M("mobile_work_time");
		$result = Db::name('mob_mobile_work_time')->where("id = 1")->update($data);
		if ($result){
			$data['status']  = 1;
			$data['msg'] = '更新成功！';
			$this->ajaxReturn($data);
		}else{
			$data['status']  = 0;
			$data['msg'] = '未知错误！';
			$this->ajaxReturn($data);
		}
	}
	
	//查询上班时间
	function workTime(){
		$username = $_REQUEST["username"];

		// $mobile_work_time = M("mobile_work_time");
		$result = Db::name('mob_mobile_work_time')->where("id = 1")->find();
		// $this->ajaxReturn($result);

		// 查询是否已签到
        $date = date('Y-m-d');
		// $sign = M('sign');
		$res = Db::name('mob_sign')->where("signtime LIKE '$date%' AND username = $username AND signout=1")->find();
		if ($res) {
			$result['sign'] = 'Y';
		} else {
			$result['sign'] = 'N';
		}

		$res2 = Db::name('mob_sign')->where("signtime LIKE '$date%' AND username = $username AND signout=2")->find();
		if ($res2) {
			$result['signout'] = 'Y';
		} else {
			$result['signout'] = 'N';
		}
		echo json_encode($result);
	}
	
	function chatHistory(){
		$targetId = $_REQUEST["targetId"];
		$username = $_REQUEST["ryId"];
		$pageIndex = $_REQUEST["pageIndex"]*$_REQUEST["pageCount"];
		$pageCount = $_REQUEST["pageCount"];
		
		$where = empty($targetId) ? " 1" : " (m.targetId = '$targetId' OR m.targetId = '$username') AND ";
		$where .= empty($username) ? " 1" : " (m.senderUserId = '$username' OR m.senderUserId = '$targetId')";
		// $mobile_chat_history = M('mobile_chat_history m');
		$result = Db::name('mob_mobile_chat_history')->alias("m")->join("xy_sys_users u","u.ryId = m.senderUserId")->field("m.*,u.cn_name,u.user_img")->where($where)->order("m.sentTime desc")->limit("$pageIndex,$pageCount")->select();
		//file_put_contents('/var/www/html/qqqqqqqqqqqqqqq.php',$mobile_chat_history->getlastsql());
		$this->ajaxReturn($result);
	}
}
?>